package com.ruoyi.zhmk.service.impl;

import java.util.Iterator;
import java.util.List;
import java.util.ArrayList;

import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.Ztree;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.StringUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.zhmk.mapper.ZhmkDeptMapper;
import com.ruoyi.zhmk.domain.ZhmkDept;
import com.ruoyi.zhmk.service.IZhmkDeptService;
import com.ruoyi.common.core.text.Convert;

/**
 * 人员部门Service业务层处理
 *
 * @author sxl
 * @date 2021-06-10
 */
@Service
public class ZhmkDeptServiceImpl implements IZhmkDeptService
{
    @Autowired
    private ZhmkDeptMapper zhmkDeptMapper;

    /**
     * 查询人员部门列表
     *
     * @param zhmkDept 人员部门
     * @return 人员部门
     */
    @Override
    public List<ZhmkDept> selectZhmkDeptList(ZhmkDept zhmkDept)
    {
        return zhmkDeptMapper.selectZhmkDeptList(zhmkDept);
    }

    /**
     * 查询人员部门树列表（自己）
     *
     * @return 所有人员部门信息
     */
    @Override
    public List<Ztree> selectZhmkDeptTree()
    {
        List<ZhmkDept> zhmkDeptList = zhmkDeptMapper.selectZhmkDeptList(new ZhmkDept());
        List<Ztree> ztrees = new ArrayList<Ztree>();
        for (ZhmkDept zhmkDept : zhmkDeptList)
        {
            if (UserConstants.DEPT_NORMAL.equals(zhmkDept.getStatus()))
            {
                Ztree ztree = new Ztree();
                ztree.setId(zhmkDept.getDeptId());
                ztree.setpId(zhmkDept.getParentId());
                ztree.setName(zhmkDept.getDeptName());
                ztree.setTitle(zhmkDept.getDeptName());
                ztrees.add(ztree);
            }
        }
        return ztrees;
    }

    /**
     * 查询部门管理树
     *
     * @param dept 部门信息
     * @return 所有部门信息
     */
    @Override
    public List<Ztree> selectDeptTree(ZhmkDept dept)
    {
        List<ZhmkDept> deptList = zhmkDeptMapper.selectZhmkDeptList(dept);
        List<Ztree> ztrees = initZtree(deptList);
        return ztrees;
    }

    /**
     * 查询部门管理树（排除下级）
     *
     * @param deptId 部门ID
     * @return 所有部门信息
     */
    @Override
    public List<Ztree> selectDeptTreeExcludeChild(ZhmkDept dept)
    {
        Long deptId = dept.getDeptId(); //修改树结构排除自己的deptId
        List<ZhmkDept> deptList = zhmkDeptMapper.selectZhmkDeptList(dept);
        Iterator<ZhmkDept> it = deptList.iterator();
        while (it.hasNext())
        {
            ZhmkDept d = (ZhmkDept) it.next();
            if (d.getDeptId().intValue() == deptId
                    || ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), deptId + ""))
            {
                it.remove();
            }
        }
        List<Ztree> ztrees = initZtree(deptList);
        return ztrees;
    }

    /**
     * 对象转部门树
     *
     * @param deptList 部门列表
     * @return 树结构列表
     */
    public List<Ztree> initZtree(List<ZhmkDept> deptList)
    {
        return initZtree(deptList, null);
    }

    /**
     * 对象转部门树
     *
     * @param deptList 部门列表
     * @param roleDeptList 角色已存在菜单列表(暂时没有添加角色权限，这个数据没有用到)
     * @return 树结构列表
     */
    public List<Ztree> initZtree(List<ZhmkDept> deptList, List<String> roleDeptList)
    {

        List<Ztree> ztrees = new ArrayList<Ztree>();
        boolean isCheck = StringUtils.isNotNull(roleDeptList);
        for (ZhmkDept dept : deptList)
        {
            if (UserConstants.DEPT_NORMAL.equals(dept.getStatus()))
            {
                Ztree ztree = new Ztree();
                ztree.setId(dept.getDeptId());
                ztree.setpId(dept.getParentId());
                ztree.setName(dept.getDeptName());
                ztree.setTitle(dept.getDeptName());
                if (isCheck)
                {
                    ztree.setChecked(roleDeptList.contains(dept.getDeptId() + dept.getDeptName()));
                }
                ztrees.add(ztree);
            }
        }
        return ztrees;
    }

    /**
     * 查询部门人数
     *
     * @param parentId 部门ID
     * @return 结果
     */
    @Override
    public int selectDeptCount(Long parentId)
    {
        ZhmkDept dept = new ZhmkDept();
        dept.setParentId(parentId);
        return zhmkDeptMapper.selectDeptCount(dept);
    }

    /**
     * 查询部门是否存在用户
     *
     * @param deptId 部门ID
     * @return 结果 true 存在 false 不存在
     */
    @Override
    public boolean checkDeptExistUser(Long deptId)
    {
        int result = zhmkDeptMapper.checkDeptExistUser(deptId);
        return result > 0 ? true : false;
    }

    /**
     * 删除人员部门信息
     *
     * @param deptId 人员部门ID
     * @return 结果
     */
    @Override
    public int deleteZhmkDeptById(Long deptId)
    {
        return zhmkDeptMapper.deleteZhmkDeptById(deptId);
    }

    /**
     * 新增人员部门
     *
     * @param zhmkDept 人员部门
     * @return 结果
     */
    @Override
    public int insertZhmkDept(ZhmkDept zhmkDept)
    {
        ZhmkDept info = zhmkDeptMapper.selectZhmkDeptById(zhmkDept.getParentId());
        // 如果父节点不为"正常"状态,则不允许新增子节点
        if (!UserConstants.DEPT_NORMAL.equals(info.getStatus()))
        {
            throw new BusinessException("部门停用，不允许新增");
        }
        zhmkDept.setAncestors(info.getAncestors() + "," + zhmkDept.getParentId());
        return zhmkDeptMapper.insertZhmkDept(zhmkDept);
    }

    /**
     * 修改人员部门
     *
     * @param zhmkDept 人员部门
     * @return 结果
     */
    @Override
    public int updateZhmkDept(ZhmkDept zhmkDept)
    {
        ZhmkDept newParentDept = zhmkDeptMapper.selectZhmkDeptById(zhmkDept.getParentId());
        ZhmkDept oldDept = selectZhmkDeptById(zhmkDept.getDeptId());
        if (StringUtils.isNotNull(newParentDept) && StringUtils.isNotNull(oldDept))
        {
            String newAncestors = newParentDept.getAncestors() + "," + newParentDept.getDeptId();
            String oldAncestors = oldDept.getAncestors();
            zhmkDept.setAncestors(newAncestors);
            updateDeptChildren(zhmkDept.getDeptId(), newAncestors, oldAncestors);
        }
        int result = zhmkDeptMapper.updateZhmkDept(zhmkDept);
        if (UserConstants.DEPT_NORMAL.equals(zhmkDept.getStatus()))
        {
            // 如果该部门是启用状态，则启用该部门的所有上级部门
            updateParentDeptStatus(zhmkDept);
        }
        return result;
    }

    /**
     * 修改该部门的父级部门状态
     *
     * @param dept 当前部门
     */
    private void updateParentDeptStatus(ZhmkDept dept)
    {
        String updateBy = dept.getUpdateBy();
        dept = zhmkDeptMapper.selectZhmkDeptById(dept.getDeptId());
        dept.setUpdateBy(updateBy);
        zhmkDeptMapper.updateDeptStatus(dept);
    }

    /**
     * 修改子元素关系
     *
     * @param deptId 被修改的部门ID
     * @param newAncestors 新的父ID集合
     * @param oldAncestors 旧的父ID集合
     */
    public void updateDeptChildren(Long deptId, String newAncestors, String oldAncestors)
    {
        List<ZhmkDept> children = zhmkDeptMapper.selectChildrenDeptById(deptId);
        for (ZhmkDept child : children)
        {
            child.setAncestors(child.getAncestors().replaceFirst(oldAncestors, newAncestors));
        }
        if (children.size() > 0)
        {
            zhmkDeptMapper.updateDeptChildren(children);
        }
    }

    /**
     * 查询人员部门
     *
     * @param deptId 人员部门ID
     * @return 人员部门
     */
    @Override
    public ZhmkDept selectZhmkDeptById(Long deptId)
    {
        return zhmkDeptMapper.selectZhmkDeptById(deptId);
    }

    /**
     * 根据ID查询所有子部门（正常状态）
     *
     * @param deptId 部门ID
     * @return 子部门数
     */
    @Override
    public int selectNormalChildrenDeptById(Long deptId)
    {
        return zhmkDeptMapper.selectNormalChildrenDeptById(deptId);
    }

    /**
     * 校验部门名称是否唯一
     *
     * @param dept 部门信息
     * @return 结果
     */
    @Override
    public String checkDeptNameUnique(ZhmkDept dept)
    {
        Long deptId = StringUtils.isNull(dept.getDeptId()) ? -1L : dept.getDeptId();
        ZhmkDept info = zhmkDeptMapper.checkDeptNameUnique(dept.getDeptName(), dept.getParentId());
        if (StringUtils.isNotNull(info) && info.getDeptId().longValue() != deptId.longValue())
        {
            return UserConstants.DEPT_NAME_NOT_UNIQUE;
        }
        return UserConstants.DEPT_NAME_UNIQUE;
    }

    /**
     * 删除人员部门对象(暂时不用)
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteZhmkDeptByIds(String ids)
    {
        return zhmkDeptMapper.deleteZhmkDeptByIds(Convert.toStrArray(ids));
    }

}
